package com.framework.common.utils;

import com.squareup.okhttp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class HttpUtils {

    protected static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static OkHttpClient client = new OkHttpClient();

    public static Response post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }

    public static Response get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }

    /**
     * get 请求
     * @param url
     * @param queryStringMap
     * @param headers
     * @return
     */
    public static Response get(String url, Map<String,String> queryStringMap, Map<String,String> headers) {
        try {
            if (queryStringMap != null) {
                if (url.lastIndexOf("?") <= -1) {
                    url += "?";
                } else {
                    url += "&";
                }
                Iterator it = headers.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
                    String name = entry.getKey();
                    String value = entry.getValue();
                    url += String.format("&{0}={1}", name, value);
                }
                url.replace("&&", "&");
            }
            OkHttpClient httpClient = new OkHttpClient();
            Request.Builder builder = new Request.Builder().url(url);
            if (headers != null) {
                Iterator it = headers.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
                    String name = entry.getKey();
                    String value = entry.getValue();
                    builder.addHeader(name, value);
                }
            }

            Request request = builder.build();
            return httpClient.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}